import { createContext, useContext, useEffect, useState } from 'react';

type Theme = 'light' | 'dark' | 'system';
type ColorTheme = 'neutral' | 'blue' | 'green' | 'purple' | 'rose' | 'orange';

interface ThemeContextType {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  actualTheme: 'light' | 'dark'; // 实际应用的主题（system会被解析为light或dark）
  colorTheme: ColorTheme;
  setColorTheme: (colorTheme: ColorTheme) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState<Theme>(() => {
    // 从 localStorage 读取保存的主题，默认为 system
    const saved = localStorage.getItem('feng-admin-theme') as Theme;
    return saved || 'system';
  });

  const [colorTheme, setColorTheme] = useState<ColorTheme>(() => {
    // 从 localStorage 读取保存的颜色主题，默认为 neutral
    const saved = localStorage.getItem('feng-admin-color-theme') as ColorTheme;
    return saved || 'neutral';
  });

  const [actualTheme, setActualTheme] = useState<'light' | 'dark'>('light');

  useEffect(() => {
    // 保存主题到 localStorage
    localStorage.setItem('feng-admin-theme', theme);

    // 获取实际应用的主题
    let resolvedTheme: 'light' | 'dark' = 'light';

    if (theme === 'system') {
      // 检测系统主题
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light';
      resolvedTheme = systemTheme;
    } else {
      resolvedTheme = theme;
    }

    setActualTheme(resolvedTheme);

    // 应用主题到 HTML 元素
    const root = document.documentElement;
    root.classList.remove('light', 'dark');
    root.classList.add(resolvedTheme);
  }, [theme]);

  useEffect(() => {
    // 保存颜色主题到 localStorage
    localStorage.setItem('feng-admin-color-theme', colorTheme);

    // 应用颜色主题到 HTML 元素
    const root = document.documentElement;
    root.classList.remove('theme-neutral', 'theme-blue', 'theme-green', 'theme-purple', 'theme-rose', 'theme-orange');
    root.classList.add(`theme-${colorTheme}`);
  }, [colorTheme]);

  // 监听系统主题变化
  useEffect(() => {
    if (theme !== 'system') return;

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

    const handleChange = (e: MediaQueryListEvent) => {
      const newTheme = e.matches ? 'dark' : 'light';
      setActualTheme(newTheme);
      const root = document.documentElement;
      root.classList.remove('light', 'dark');
      root.classList.add(newTheme);
    };

    mediaQuery.addEventListener('change', handleChange);

    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, setTheme, actualTheme, colorTheme, setColorTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

